// 页面初始化处理菜单

import router from "@/router"
import { mapMutations } from "vuex"
import context from "@/main"
import { getMyPermissions, getMyMenus } from '@/api/login'

const { SET_MENU, SET_INTERFACES } = mapMutations(["SET_MENU", "SET_INTERFACES"])

// 过滤掉的详情路由（默认详情页路由不在左边的导航栏渲染出来）,如果后续需要添加的话，修改这个数据即可  数组值是路由路径
const detailList = [
  '/menu/merchant-examine/examine-detail',
  '/menu/merchant-admin/change-card',
  '/menu/report-admin/notice-detail',
  '/menu/merchant-admin/admin-detail',
  '/menu/reconciliation-and-settlement/reconciliation-detail',
  '/menu/merchant-admin/change-data',
  '/menu/report-admin/product-list',
  '/menu/report-admin/silver-fill-detail'
]

// 整合菜单和动态添加路由
const mergeMenu = () => {
  return new Promise((resolve, reject) => {
    try {
      Promise.all([getMyPermissions(), getMyMenus()]).then(([interfaces, myMenus]) => {
        SET_INTERFACES.apply(context, [interfaces])
        let DynamicRoutes = []
        handleMenu(myMenus)
        myMenus.map((i) => {
          // 添加标识，用来区分是否是详情页（）
          i.isDetail = detailList.includes(i.path)
          if (!i.children) {
            DynamicRoutes.push(i)
          }
        })
        myMenus = generateMenu(myMenus)
        let { routes } = router.options
        // 动态渲染路由
        DynamicRoutes.forEach(item => {
          debugger
          item.component = () => import(`@/views/${item.component_path}`)
          const { title, id, idList } = item
          item.meta = {
            title,
            id,
            idList
          }
          routes[2].children.push(item)
        })
        // 设置左边导航栏
        SET_MENU.apply(context, [myMenus])
        router.addRoutes(routes)
        resolve(routes[2].children[0].path)
      })
    } catch (e) {
      reject(e)
    }
  })
}

// 处理菜单
const handleMenu = (data) => {
  for (let i = 0; i < data.length; i++) {
    const item = data[i]
    for (let j = 0; j < data.length; j++) {
      const item1 = data[j]
      if (item.id === item1.parent_id) {
        item.idList = item.idList || []
        item.children = item.children || []
        // 通过idList变量，用来存储层级关系
        item1.idList = [...item.idList, item.id]
        item.children.push(item1)
      }
    }
  }
}

// 生成菜单
const generateMenu = (data) => {
  let menus = []
  data.forEach(item => {
    if (item.parent_id === 0) {
      menus.push(item)
    }
  })
  return menus
}

export { mergeMenu, handleMenu, generateMenu, detailList }
